﻿using System;
using System.ComponentModel;
using System.IO;

using FileTreeSpace;

namespace Trav
{
    public partial class TravModel
    {
        // This class gets passed by the opener thread to communicate parameters and results.
        private class openerArgs
        {
            public DirRoot Tree;
            public string PathName;
            public string FullName;
            public bool IsFile = false;
            public string Failure;
        }

        private void openerWork (object sender, DoWorkEventArgs e)
        {
            openerArgs args = new openerArgs ();
            args.FullName = (string) e.Argument;
            e.Result = args;

            try
            {
                // Normalize name to full path.
                args.FullName = Path.GetFullPath ((string) e.Argument);
            }
            catch (Exception ex)
            {
                args.Failure = ex.Message;
                return;
            }

            if (args.Failure != null)
                return;

            args.IsFile = File.Exists (args.FullName);
            if (args.IsFile)
                args.PathName = Path.GetDirectoryName (args.FullName);
            else
                args.PathName = args.FullName;

            try
            {
                args.Tree = new DirRoot (args.PathName);
                args.Tree.Watch ();
            }
            catch (Exception ex)
            {
                args.Failure = ex.Message;
            }
        }


        private void openerComplete (object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled || e.Error != null)
            {
                ShowStatus ("Open failed");
                return;
            }

            openerArgs args = e.Result as openerArgs;

            if (args.Failure != null)
            {
                ShowStatus ("Could not open '" + args.FullName + "' - " + args.Failure);
                return;
            }

            args.Tree.DirCreateSubs += DirCreater;
            args.Tree.DirRenameSubs += DirRenamer;
            args.Tree.DirDeleteSubs += DirDeleter;
            args.Tree.FileCreateSubs += FileCreater;
            args.Tree.FileChangeSubs += FileChanger;
            args.Tree.FileRenameSubs += FileRenamer;
            args.Tree.FileDeleteSubs += FileDeleter;

            Tree = args.Tree;
            OnFolderOpened (args.Tree);

            if (args.IsFile && Path.GetExtension (args.FullName).ToLower () == ".m3u")
            {
                ShowSubfolders (true);
                ChangeCurrentDir (Tree.Name);
                SelectFromPlaylist (args.FullName);
            }

            ShowStatus ("Loaded " + args.FullName);
        }
    }
}
